package com.bigegg.employee.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

public class CommonUtil {

    /**
     * 得到resource目录下某资源的绝对路
     **/

    public static String getResourcePath(String filePath){

        String retVal = null;

        if(StringUtils.isEmpty(filePath)){

            return null;

        }

        try {

            Resource resource = new ClassPathResource(filePath);
            retVal = resource.getFile().getAbsolutePath();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;
    }

    /**
     * 耗时
     * @param ms
     * @return
     */
    public static String ms2Hms(long ms){

        //          毫秒        秒                分            时
        long hour = ms / 1000 / 60 / 60;

        //         毫秒        秒                分
        long min = ms / 1000 / 60 % 60;

        //         毫秒        秒
        long sec = ms / 1000 % 60;

        //        毫秒        秒
        long mi = ms % 1000;

        String x = "";

        if(hour>0){
            x += hour + "时";
        }

        if(min>0){
            x += min + "分";
        }

        if(sec>0){
            x += sec + "秒";
        }

        if(mi>0){
            x += mi + "毫秒";
        }

        // System.out.println(x);

        return x;

    }

    /**
     * 下载模板文件
     */
    public static void downloadResource(String path , HttpServletResponse response){

        try{
            // 读到流中
            InputStream inputStream = CommonUtil.class.getClassLoader().getResourceAsStream(path);
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = path.substring(path.lastIndexOf("/"),path.length());
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
